﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NBusiness.Query;

namespace NBusiness.Data.Providers.SqlServer.Query
{
    class SqlUpdate : SqlParameters, IUpdate, IAssignable
    {
        private ITable _table;
        private IExpression _where;
        private List<IAssignment> _assignments = new List<IAssignment>();

        #region IUpdate Members

        public IAssignable Table(ITable table)
        {
            _table = table;
            return this;
        }

        #endregion

        #region IRelationalElement Members

        public string ToSql()
        {
            return ToSql(new SqlQueryContext(AliasAssignmentStyle.None));
        }

        public string ToSql(IQueryContext context)
        {
            if (_assignments.Count < 1)
                throw new InvalidOperationException("Must specify at least 1 assignment");

            StringBuilder builder = new StringBuilder("UPDATE ");
            builder.Append(_table.ToSql(context));
            builder.Append(" SET ");

            for (int x = 0; x < _assignments.Count; x++)
            {
                if (x > 0)
                    builder.Append(",");

                builder.Append(_assignments[x].ToSql(context));
            }

            builder.Append(" WHERE ");
            builder.Append(_where.ToSql(context));

            return builder.ToString();
        }

        #endregion

        #region IAssignable Members

        public IAssignable Set(IEvaluatable left, object right)
        {
            SqlAssignment assignment = new SqlAssignment(left, SqlEvaluatable.Coerce(right));
            _assignments.Add(assignment);
            return this;
        }

        public void Where(IExpression expression)
        {
            _where = expression;
        }

        #endregion
    }
}
